<?php
/**
 * Created by PhpStorm.
 * User: MSQ
 * Date: 2021/9/27
 * Time: 16:54
 */

namespace App\Handler\WebSocket;


use App\Model\Baiyou\ApiAccessToken;
use App\Utils\RedisHelp;
use App\Utils\WebSocketMessage;
use EasySwoole\EasySwoole\Config;

class ByAuthHandler extends BaseHandler
{
    /**
     * 白友登录 {"msgType":"byAuth","checkType":1,"content":{"projectId":1,"token":""}}
     * @return string
     */
    public function handler(): string
    {
        $projectId = $this->content['projectId'] ?? 0;
        if (empty($projectId)) {
            $data = WebSocketMessage::getErrorMessage("项目ID不能为空");
            return $data;
        }

        $token = $this->content['token'] ?? '';
        $timestamp = (int)substr($token, strrpos($token, '_') + 1);
        $expire = Config::getInstance()->getConf("USER.accessTokenExpire");

        // 验证有效期
        if ($timestamp + $expire <= time()) {
            $data = WebSocketMessage::getErrorMessage("您的登录验证已经过期，请重新登录【token: {$token}】");
            return $data;
        }

        $accessToken = ApiAccessToken::create()->get([
            'access_token' => $token,
        ]);
        if (empty($accessToken)) {
            $data = WebSocketMessage::getErrorMessage("token不存在");
            return $data;
        }

        $redisHelp = new RedisHelp();
        // 项目fd集合
        $redisHelp->setByProjectFd($projectId, $this->fd);
        // fd信息
        $redisHelp->setByFd($this->fd, [
            'project_id' => $projectId,
            'check_type' => WebSocketMessage::CheckTypeBy,
        ]);

        $data = WebSocketMessage::getMessage(WebSocketMessage::ByAuthRes, 'ok');
        return $data;
    }
}
